package com.yangzb.spring.batch;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;


@Slf4j
public class JdbcRowMapper implements RowMapper<Map> {

    private AtomicInteger count = new AtomicInteger();

    public Map mapRow(ResultSet rs, int rowNum) throws SQLException {
        Map row = new HashMap();
        ResultSetMetaData rsmd = rs.getMetaData();
        rsmd.getColumnCount();
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            String cl = rsmd.getColumnLabel(i);
            int columnType = rs.getMetaData().getColumnType(i);
            switch (columnType) {
                case Types.BIT:
                    row.put(cl, rs.getBoolean(cl));
                    break;
                case Types.INTEGER:
                    row.put(cl, rs.getInt(cl));
                    break;
                case Types.BIGINT:
                    row.put(cl, rs.getLong(cl));
                    break;
                default:
                    row.put(cl, rs.getString(cl));
            }
        }
        count.getAndIncrement();
        if (count.get() % 10000 == 0) {
            log.info("read {}", count.get());
        }
        return row;
    }

}
